package top.atcra.rpc.protection.loadBalancer.selector.impl;

import io.netty.channel.Channel;
import top.atcra.rpc.protection.loadBalancer.selector.ServiceSelector;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.TreeMap;

public class MinResponseTimeSelector extends ServiceSelector {

    // 尚未执行心跳检查时，退化为轮询选择器
    protected final RoundRobinServiceSelector selector;

    public MinResponseTimeSelector(List<InetSocketAddress> addresses) {
        super(addresses);
        selector = new RoundRobinServiceSelector(addresses);
    }

    TreeMap<Long, Channel> CHANNEL_TTL_CACHE;

    public MinResponseTimeSelector setTTLCache(TreeMap<Long, Channel> cache) {
        this.CHANNEL_TTL_CACHE = cache;
        return this;
    }

    @Override
    public InetSocketAddress getAddress(Object key) {
        var entry = CHANNEL_TTL_CACHE.firstEntry();
        if (entry != null) {
            return (InetSocketAddress) entry.getValue().remoteAddress();
        } else {
            // 尚未执行心跳检查时，退化为轮询选择器
            return selector.getAddress(key);
        }

    }
}
